import {
  MEMBER_LEVEL_RIGHT_LIST,
  MEMBER_LEVEL_MAP,
} from 'sub/assets/constant/view-constants';
import { behavior as computedBehavior } from 'miniprogram-computed';
import { membershipStore } from '@/stores/membership-store';
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings';
// @ts-ignore
import { getStorageItem } from '@/utils/storage';

Page({
  behaviors: [computedBehavior, storeBindingsBehavior],
  storeBindings: {
    store: membershipStore,
    fields: ['level', 'levelTaskList'],
    actions: ['getLevelTaskInfo'],
  },
  data: {
    /** 当前显示的等级卡片的索引 */
    currentSwiperIndex: 0,
    /** 头像地址 */
    avatarUrl: '',
    /** 昵称 */
    nickName: '',
  },
  computed: {
    /** 当前显示的礼物收益比例 */
    currentGiftRatio(data: typeof this.data) {
      return MEMBER_LEVEL_MAP.get((data.currentSwiperIndex + 1).toString())
        ?.giftRatio;
    },
    /** 当前显示的权益列表 */
    currentRights(data: typeof this.data) {
      const level10Rights = MEMBER_LEVEL_MAP.get('10')?.rights;

      // 当前等级小于等于10级时，显示10级的权益
      if (data.currentSwiperIndex <= 9) {
        return MEMBER_LEVEL_RIGHT_LIST.filter((item) => {
          return level10Rights?.includes(item.title);
        }).map((item) => {
          return {
            ...item,
            isUnlocked: data.unlockedRights?.includes(item.title),
          };
        });
      }

      // 当前等级大于10级时，显示10级之后的权益
      return MEMBER_LEVEL_RIGHT_LIST.filter((item) => {
        return !level10Rights?.includes(item.title);
      }).map((item) => {
        return {
          ...item,
          isUnlocked: data.unlockedRights?.includes(item.title),
        };
      });
    },
    /** 已解锁的权益，根据当前显示的卡片变动 */
    unlockedRights(data: typeof this.data) {
      return MEMBER_LEVEL_MAP.get((data.currentSwiperIndex + 1).toString())
        ?.rights;
    },
    /** 当前显示的升级任务是否需要全部完成才能升级 */
    isNeedAllTaskCompleted(data: typeof this.data) {
      return data.levelTaskList?.[data.currentSwiperIndex]?.isNeedAllCompleted;
    },
    /** 当前显示的升级任务 */
    currentTask(data: typeof this.data) {
      console.log(data?.levelTaskList?.[data.currentSwiperIndex]?.taskList,'001');
      return data?.levelTaskList?.[data.currentSwiperIndex]?.taskList || [];
    },
  },
  async onLoad() {
    this.init();
    await this.getLevelTaskInfo();
    this.updateStoreBindings();
    this.moveLevelCard(this.data.level);
  },
  /** 移动等级卡片到对应的等级
   * @param {number} levelIndex 等级索引
   */
  moveLevelCard(levelIndex: number) {
    console.log('moveLevelCard', levelIndex);
    this.selectComponent('#levelSwiper').moveSwiper(levelIndex);
  },
  /** 跳转到「升级奖励」页面 */
  jumpToLevelUpBonuses() {
    wx.navigateTo({
      url: '/subpkg/pages/level-up-bonuses/level-up-bonuses',
    });
  },
  /** 「升级任务」按钮点击事件 */
  async onTaskButtonClick() {
    const currentSwiperIndex = this.data.currentSwiperIndex;
    if (currentSwiperIndex !== this.data.level) {
      this.moveLevelCard(this.data.level);
      await new Promise((resolve) => setTimeout(resolve, 300));
    }

    if (this.data.level === 17) {
      this.openCongratsMaxLevelPopup();
    }

    // 页面滚动到底部
    wx.pageScrollTo({
      duration: 300,
      selector: '.task-panel',
    });
  },
  /**
   * 初始化
   * 1. 将当前显示的等级卡片的索引设置为当前等级
   * 2. 设置头像和昵称
   */
  init() {
    this.setData({
      currentSwiperIndex: this.data.level,
    });
    this.setData({
      avatarUrl: getStorageItem('headerImgPath'),
      nickName: getStorageItem('user_name'),
    });
  },
  /** 打开恭喜达到最高级弹窗 */
  openCongratsMaxLevelPopup() {
    this.selectComponent('#congratsMaxLevelPopup').open();
  },
  /** 打开绑定微信弹窗 */
  openBindWechatPopup() {
    this.selectComponent('#bindWechatPopup').open();
  },
  /** 打开「下载嗨喵APP」弹窗 */
  openDownloadAppPopup() {
    this.selectComponent('#downloadAppPopup').open();
  },
  /**
   * 任务项点击右侧按钮事件
   * @param {object} e 事件对象
   */
  onTaskItemButtonClick(e: WechatMiniprogram.TouchEvent) {
    const isCompleted = e.currentTarget.dataset.isCompleted;
    if (isCompleted) return;

    const taskType = e.currentTarget.dataset.taskType as TaskType;
    console.log('taskType', taskType);
    switch (taskType) {
      case 'bindWechat':
        this.openBindWechatPopup();
        break;
      case 'realNameAuthentication':
        wx.navigateTo({
          url: '/pages/identification/identification',
        });
        break;
      case 'createActivity':
        wx.navigateTo({
          url: '/pages/index/applyActivity/applyActivity',
        });
        break;
      case 'invite':
        wx.navigateTo({
          url: '/pages/invite/invite',
        });
        break;
      case 'loginApp':
        this.openDownloadAppPopup();
        break;
      default:
        break;
    }
  },
});
